import Vue from 'vue'
import VueRouter from 'vue-router'
import {Dialog}  from 'vant'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login'),
    meta: { requiresAuth: false} //给路由添加额外的自定义数据
  },
  {
    // 一级路由渲染到根组件中的router-view 
    path: '/',
    component: () => import('@/views/layout/layout'),
    children: [
      {
        path: '',  //默认子路由
        name: 'home',
        component: () => import('@/views/home/home'),
        meta: { requiresAuth: false}
      },
      {
        path: '/question',  
        name: 'question',
        component: () => import('@/views/question/question'),
        meta: { requiresAuth: false}
      },
      {
        path: '/video',  
        name: 'video',
        component: () => import('@/views/video/video'),
        meta: { requiresAuth: false}
      },
      {
        path: '/user',  
        name: 'user',
        component: () => import('@/views/user/user'),
        meta: { requiresAuth: false}
      }
    ]
  },
  {
    path: '/search',
    name: 'Search',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "search" */ '@/views/search/search'),
    meta: { requiresAuth: false}
  },
  {
    // 通过params传参
    path: "/article/:articleId",
    // 通过query传参
    // path: "/article",
    name: "ArticleDetail",
    component: () => import('@/views/article/articleDetail'),
    // 将动态路由参数映射到组件的props中，无论是访问还是维护性都很方便
    // 这个只有通过params传参，才能通过props拿到，query拿不到
    props: true,
    meta: { requiresAuth: false}
  },
  {
    path:"/user/profile",
    name: "UserProfile",
    component: () => import('@/views/userProfile/user-profile'),
    meta: { requiresAuth: true}
  },
  {
    path:"/user/chat",
    name: "UserChat",
    component: () => import('@/views/user-chat/user-chat'),
    meta: { requiresAuth: true}
  }
]

const router = new VueRouter({
  routes
})

// 全局导航守卫
// to: 要访问的页面路由信息
// from: 来自哪个页面的路由信息
// next: 放行的标记
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (store.state.user) {
      return next()
    }
    // 没有登录 
    // 校验登录状态，提示用户
    Dialog.confirm({
      title: "访问提示",
      message: "该功能需要登录才能访问，确认登录吗"
    }).then(() => {
      // 确认执行这里
      if (to.path !== '/login') {
        next({
          path: '/login',
          query: {
            // 将要跳转路由的path作为参数，传递到登录页面
            redirect: to.fullPath
          }
        })
      }
      // router.replace('/login')

      // router.replace({
      //   path: "/login",
      //   query: {
      //     redirect: router.currentRoute.fullPath
      //   }
      // })
      
      // next()
    }).catch(() => {
      // 取消执行这里
      // 取消了，停止路由导航
      next(false)
    }) 
  } else {
    // 不需要登录状态的页面，直接过去，放行
    next()
  }
})
export default router
